/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.VirtualMachineInst;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.VirtualMachineConf;
import it.polimi.games.epkb.entityClasses.Component;
import it.polimi.games.epkb.entityClasses.ServiceInstance;
import java.util.ArrayList;
import java.util.Collection;
import it.polimi.games.epkb.entityClasses.VirtualMachineResources;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class VirtualMachineInstJpaController implements Serializable {

    public VirtualMachineInstJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }
    public VirtualMachineInstJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(VirtualMachineInst virtualMachineInst) throws IllegalOrphanException, PreexistingEntityException, Exception {
        if (virtualMachineInst.getServiceInstanceCollection() == null) {
            virtualMachineInst.setServiceInstanceCollection(new ArrayList<ServiceInstance>());
        }
        if (virtualMachineInst.getVirtualMachineResourcesCollection() == null) {
            virtualMachineInst.setVirtualMachineResourcesCollection(new ArrayList<VirtualMachineResources>());
        }
        List<String> illegalOrphanMessages = null;
        Component componentOrphanCheck = virtualMachineInst.getComponent();
        if (componentOrphanCheck != null) {
            VirtualMachineInst oldVirtualMachineInstOfComponent = componentOrphanCheck.getVirtualMachineInst();
            if (oldVirtualMachineInstOfComponent != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The Component " + componentOrphanCheck + " already has an item of type VirtualMachineInst whose component column cannot be null. Please make another selection for the component field.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            VirtualMachineConf idVMConf = virtualMachineInst.getIdVMConf();
            if (idVMConf != null) {
                idVMConf = em.getReference(idVMConf.getClass(), idVMConf.getId());
                virtualMachineInst.setIdVMConf(idVMConf);
            }
            Component component = virtualMachineInst.getComponent();
            if (component != null) {
                component = em.getReference(component.getClass(), component.getId());
                virtualMachineInst.setComponent(component);
            }
            Collection<ServiceInstance> attachedServiceInstanceCollection = new ArrayList<ServiceInstance>();
            for (ServiceInstance serviceInstanceCollectionServiceInstanceToAttach : virtualMachineInst.getServiceInstanceCollection()) {
                serviceInstanceCollectionServiceInstanceToAttach = em.getReference(serviceInstanceCollectionServiceInstanceToAttach.getClass(), serviceInstanceCollectionServiceInstanceToAttach.getId());
                attachedServiceInstanceCollection.add(serviceInstanceCollectionServiceInstanceToAttach);
            }
            virtualMachineInst.setServiceInstanceCollection(attachedServiceInstanceCollection);
            Collection<VirtualMachineResources> attachedVirtualMachineResourcesCollection = new ArrayList<VirtualMachineResources>();
            for (VirtualMachineResources virtualMachineResourcesCollectionVirtualMachineResourcesToAttach : virtualMachineInst.getVirtualMachineResourcesCollection()) {
                virtualMachineResourcesCollectionVirtualMachineResourcesToAttach = em.getReference(virtualMachineResourcesCollectionVirtualMachineResourcesToAttach.getClass(), virtualMachineResourcesCollectionVirtualMachineResourcesToAttach.getVirtualMachineResourcesPK());
                attachedVirtualMachineResourcesCollection.add(virtualMachineResourcesCollectionVirtualMachineResourcesToAttach);
            }
            virtualMachineInst.setVirtualMachineResourcesCollection(attachedVirtualMachineResourcesCollection);
            em.persist(virtualMachineInst);
            if (idVMConf != null) {
                idVMConf.getVirtualMachineInstCollection().add(virtualMachineInst);
                idVMConf = em.merge(idVMConf);
            }
            if (component != null) {
                component.setVirtualMachineInst(virtualMachineInst);
                component = em.merge(component);
            }
            for (ServiceInstance serviceInstanceCollectionServiceInstance : virtualMachineInst.getServiceInstanceCollection()) {
                VirtualMachineInst oldIdVMInstanceOfServiceInstanceCollectionServiceInstance = serviceInstanceCollectionServiceInstance.getIdVMInstance();
                serviceInstanceCollectionServiceInstance.setIdVMInstance(virtualMachineInst);
                serviceInstanceCollectionServiceInstance = em.merge(serviceInstanceCollectionServiceInstance);
                if (oldIdVMInstanceOfServiceInstanceCollectionServiceInstance != null) {
                    oldIdVMInstanceOfServiceInstanceCollectionServiceInstance.getServiceInstanceCollection().remove(serviceInstanceCollectionServiceInstance);
                    oldIdVMInstanceOfServiceInstanceCollectionServiceInstance = em.merge(oldIdVMInstanceOfServiceInstanceCollectionServiceInstance);
                }
            }
            for (VirtualMachineResources virtualMachineResourcesCollectionVirtualMachineResources : virtualMachineInst.getVirtualMachineResourcesCollection()) {
                VirtualMachineInst oldVirtualMachineInstOfVirtualMachineResourcesCollectionVirtualMachineResources = virtualMachineResourcesCollectionVirtualMachineResources.getVirtualMachineInst();
                virtualMachineResourcesCollectionVirtualMachineResources.setVirtualMachineInst(virtualMachineInst);
                virtualMachineResourcesCollectionVirtualMachineResources = em.merge(virtualMachineResourcesCollectionVirtualMachineResources);
                if (oldVirtualMachineInstOfVirtualMachineResourcesCollectionVirtualMachineResources != null) {
                    oldVirtualMachineInstOfVirtualMachineResourcesCollectionVirtualMachineResources.getVirtualMachineResourcesCollection().remove(virtualMachineResourcesCollectionVirtualMachineResources);
                    oldVirtualMachineInstOfVirtualMachineResourcesCollectionVirtualMachineResources = em.merge(oldVirtualMachineInstOfVirtualMachineResourcesCollectionVirtualMachineResources);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findVirtualMachineInst(virtualMachineInst.getId()) != null) {
                throw new PreexistingEntityException("VirtualMachineInst " + virtualMachineInst + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(VirtualMachineInst virtualMachineInst) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            VirtualMachineInst persistentVirtualMachineInst = em.find(VirtualMachineInst.class, virtualMachineInst.getId());
            VirtualMachineConf idVMConfOld = persistentVirtualMachineInst.getIdVMConf();
            VirtualMachineConf idVMConfNew = virtualMachineInst.getIdVMConf();
            Component componentOld = persistentVirtualMachineInst.getComponent();
            Component componentNew = virtualMachineInst.getComponent();
            Collection<ServiceInstance> serviceInstanceCollectionOld = persistentVirtualMachineInst.getServiceInstanceCollection();
            Collection<ServiceInstance> serviceInstanceCollectionNew = virtualMachineInst.getServiceInstanceCollection();
            Collection<VirtualMachineResources> virtualMachineResourcesCollectionOld = persistentVirtualMachineInst.getVirtualMachineResourcesCollection();
            Collection<VirtualMachineResources> virtualMachineResourcesCollectionNew = virtualMachineInst.getVirtualMachineResourcesCollection();
            List<String> illegalOrphanMessages = null;
            if (componentNew != null && !componentNew.equals(componentOld)) {
                VirtualMachineInst oldVirtualMachineInstOfComponent = componentNew.getVirtualMachineInst();
                if (oldVirtualMachineInstOfComponent != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The Component " + componentNew + " already has an item of type VirtualMachineInst whose component column cannot be null. Please make another selection for the component field.");
                }
            }
            for (VirtualMachineResources virtualMachineResourcesCollectionOldVirtualMachineResources : virtualMachineResourcesCollectionOld) {
                if (!virtualMachineResourcesCollectionNew.contains(virtualMachineResourcesCollectionOldVirtualMachineResources)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain VirtualMachineResources " + virtualMachineResourcesCollectionOldVirtualMachineResources + " since its virtualMachineInst field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idVMConfNew != null) {
                idVMConfNew = em.getReference(idVMConfNew.getClass(), idVMConfNew.getId());
                virtualMachineInst.setIdVMConf(idVMConfNew);
            }
            if (componentNew != null) {
                componentNew = em.getReference(componentNew.getClass(), componentNew.getId());
                virtualMachineInst.setComponent(componentNew);
            }
            Collection<ServiceInstance> attachedServiceInstanceCollectionNew = new ArrayList<ServiceInstance>();
            for (ServiceInstance serviceInstanceCollectionNewServiceInstanceToAttach : serviceInstanceCollectionNew) {
                serviceInstanceCollectionNewServiceInstanceToAttach = em.getReference(serviceInstanceCollectionNewServiceInstanceToAttach.getClass(), serviceInstanceCollectionNewServiceInstanceToAttach.getId());
                attachedServiceInstanceCollectionNew.add(serviceInstanceCollectionNewServiceInstanceToAttach);
            }
            serviceInstanceCollectionNew = attachedServiceInstanceCollectionNew;
            virtualMachineInst.setServiceInstanceCollection(serviceInstanceCollectionNew);
            Collection<VirtualMachineResources> attachedVirtualMachineResourcesCollectionNew = new ArrayList<VirtualMachineResources>();
            for (VirtualMachineResources virtualMachineResourcesCollectionNewVirtualMachineResourcesToAttach : virtualMachineResourcesCollectionNew) {
                virtualMachineResourcesCollectionNewVirtualMachineResourcesToAttach = em.getReference(virtualMachineResourcesCollectionNewVirtualMachineResourcesToAttach.getClass(), virtualMachineResourcesCollectionNewVirtualMachineResourcesToAttach.getVirtualMachineResourcesPK());
                attachedVirtualMachineResourcesCollectionNew.add(virtualMachineResourcesCollectionNewVirtualMachineResourcesToAttach);
            }
            virtualMachineResourcesCollectionNew = attachedVirtualMachineResourcesCollectionNew;
            virtualMachineInst.setVirtualMachineResourcesCollection(virtualMachineResourcesCollectionNew);
            virtualMachineInst = em.merge(virtualMachineInst);
            if (idVMConfOld != null && !idVMConfOld.equals(idVMConfNew)) {
                idVMConfOld.getVirtualMachineInstCollection().remove(virtualMachineInst);
                idVMConfOld = em.merge(idVMConfOld);
            }
            if (idVMConfNew != null && !idVMConfNew.equals(idVMConfOld)) {
                idVMConfNew.getVirtualMachineInstCollection().add(virtualMachineInst);
                idVMConfNew = em.merge(idVMConfNew);
            }
            if (componentOld != null && !componentOld.equals(componentNew)) {
                componentOld.setVirtualMachineInst(null);
                componentOld = em.merge(componentOld);
            }
            if (componentNew != null && !componentNew.equals(componentOld)) {
                componentNew.setVirtualMachineInst(virtualMachineInst);
                componentNew = em.merge(componentNew);
            }
            for (ServiceInstance serviceInstanceCollectionOldServiceInstance : serviceInstanceCollectionOld) {
                if (!serviceInstanceCollectionNew.contains(serviceInstanceCollectionOldServiceInstance)) {
                    serviceInstanceCollectionOldServiceInstance.setIdVMInstance(null);
                    serviceInstanceCollectionOldServiceInstance = em.merge(serviceInstanceCollectionOldServiceInstance);
                }
            }
            for (ServiceInstance serviceInstanceCollectionNewServiceInstance : serviceInstanceCollectionNew) {
                if (!serviceInstanceCollectionOld.contains(serviceInstanceCollectionNewServiceInstance)) {
                    VirtualMachineInst oldIdVMInstanceOfServiceInstanceCollectionNewServiceInstance = serviceInstanceCollectionNewServiceInstance.getIdVMInstance();
                    serviceInstanceCollectionNewServiceInstance.setIdVMInstance(virtualMachineInst);
                    serviceInstanceCollectionNewServiceInstance = em.merge(serviceInstanceCollectionNewServiceInstance);
                    if (oldIdVMInstanceOfServiceInstanceCollectionNewServiceInstance != null && !oldIdVMInstanceOfServiceInstanceCollectionNewServiceInstance.equals(virtualMachineInst)) {
                        oldIdVMInstanceOfServiceInstanceCollectionNewServiceInstance.getServiceInstanceCollection().remove(serviceInstanceCollectionNewServiceInstance);
                        oldIdVMInstanceOfServiceInstanceCollectionNewServiceInstance = em.merge(oldIdVMInstanceOfServiceInstanceCollectionNewServiceInstance);
                    }
                }
            }
            for (VirtualMachineResources virtualMachineResourcesCollectionNewVirtualMachineResources : virtualMachineResourcesCollectionNew) {
                if (!virtualMachineResourcesCollectionOld.contains(virtualMachineResourcesCollectionNewVirtualMachineResources)) {
                    VirtualMachineInst oldVirtualMachineInstOfVirtualMachineResourcesCollectionNewVirtualMachineResources = virtualMachineResourcesCollectionNewVirtualMachineResources.getVirtualMachineInst();
                    virtualMachineResourcesCollectionNewVirtualMachineResources.setVirtualMachineInst(virtualMachineInst);
                    virtualMachineResourcesCollectionNewVirtualMachineResources = em.merge(virtualMachineResourcesCollectionNewVirtualMachineResources);
                    if (oldVirtualMachineInstOfVirtualMachineResourcesCollectionNewVirtualMachineResources != null && !oldVirtualMachineInstOfVirtualMachineResourcesCollectionNewVirtualMachineResources.equals(virtualMachineInst)) {
                        oldVirtualMachineInstOfVirtualMachineResourcesCollectionNewVirtualMachineResources.getVirtualMachineResourcesCollection().remove(virtualMachineResourcesCollectionNewVirtualMachineResources);
                        oldVirtualMachineInstOfVirtualMachineResourcesCollectionNewVirtualMachineResources = em.merge(oldVirtualMachineInstOfVirtualMachineResourcesCollectionNewVirtualMachineResources);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = virtualMachineInst.getId();
                if (findVirtualMachineInst(id) == null) {
                    throw new NonexistentEntityException("The virtualMachineInst with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            VirtualMachineInst virtualMachineInst;
            try {
                virtualMachineInst = em.getReference(VirtualMachineInst.class, id);
                virtualMachineInst.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The virtualMachineInst with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<VirtualMachineResources> virtualMachineResourcesCollectionOrphanCheck = virtualMachineInst.getVirtualMachineResourcesCollection();
            for (VirtualMachineResources virtualMachineResourcesCollectionOrphanCheckVirtualMachineResources : virtualMachineResourcesCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This VirtualMachineInst (" + virtualMachineInst + ") cannot be destroyed since the VirtualMachineResources " + virtualMachineResourcesCollectionOrphanCheckVirtualMachineResources + " in its virtualMachineResourcesCollection field has a non-nullable virtualMachineInst field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            VirtualMachineConf idVMConf = virtualMachineInst.getIdVMConf();
            if (idVMConf != null) {
                idVMConf.getVirtualMachineInstCollection().remove(virtualMachineInst);
                idVMConf = em.merge(idVMConf);
            }
            Component component = virtualMachineInst.getComponent();
            if (component != null) {
                component.setVirtualMachineInst(null);
                component = em.merge(component);
            }
            Collection<ServiceInstance> serviceInstanceCollection = virtualMachineInst.getServiceInstanceCollection();
            for (ServiceInstance serviceInstanceCollectionServiceInstance : serviceInstanceCollection) {
                serviceInstanceCollectionServiceInstance.setIdVMInstance(null);
                serviceInstanceCollectionServiceInstance = em.merge(serviceInstanceCollectionServiceInstance);
            }
            em.remove(virtualMachineInst);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<VirtualMachineInst> findVirtualMachineInstEntities() {
        return findVirtualMachineInstEntities(true, -1, -1);
    }

    public List<VirtualMachineInst> findVirtualMachineInstEntities(int maxResults, int firstResult) {
        return findVirtualMachineInstEntities(false, maxResults, firstResult);
    }

    private List<VirtualMachineInst> findVirtualMachineInstEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(VirtualMachineInst.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public VirtualMachineInst findVirtualMachineInst(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(VirtualMachineInst.class, id);
        } finally {
            em.close();
        }
    }

    public int getVirtualMachineInstCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<VirtualMachineInst> rt = cq.from(VirtualMachineInst.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
